import os, time, sys
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from django.conf import settings

from utils.exception import CustomError


def SaveTempFile(file, filename):
    folder_path = settings.MEDIA_ROOT
    # 判断图片文件夹是否存在
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    # 删除历史图片
    now = int(time.time())
    old_files = os.listdir(folder_path)
    for old_file in old_files:
        old_file_path = os.path.join(folder_path, old_file)
        try:
            if os.path.isfile(old_file_path):
                last = int(os.stat(old_file_path).st_atime)
                if now - last > 180:
                    os.remove(old_file_path)
        except:
            pass

    full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
    with open(full_filename, 'wb+') as fb:
        for chunk in file.chunks():
            fb.write(chunk)
    return full_filename


class TenCenCos():
    def __init__(self):
        self.secret_id = settings.TENCENT_CLOUD['TENCENT_SECRETID']  # 替换为用户的secret_id
        self.secret_key = settings.TENCENT_CLOUD['TENCENT_SECRETKEY']  # 替换为用户的secret_key
        self.region = settings.TENCENT_CLOUD['REGION']  # 替换为用户的region
        self.config = CosConfig(Region=self.region, SecretId=self.secret_id, SecretKey=self.secret_key,
                                Token=None)  # 获取配置对象
        self.client = CosS3Client(self.config)

    def upload(self, local_filepath, save_path):
        # 本地路径 简单上传
        try:
            # response = self.client.put_object_from_local_file(
            #     Bucket=settings.TENCENT_CLOUD['BUCKET'],
            #     LocalFilePath=local_filepath,
            #     Key=save_path,
            # )
            response = self.client.upload_file(
                Bucket=settings.TENCENT_CLOUD['BUCKET'],
                LocalFilePath=local_filepath,
                Key=save_path,
                PartSize=10,
                MAXThread=10
            )
            # print(response)
        except Exception as e:
            raise CustomError('文件上传失败')

        '''
        {'Content-Length': '0', 'Connection': 'keep-alive', 'Date': 'Sat, 18 Jul 2020 09:02:06 GMT', 
        'ETag': '"c89bae6e7f3ec6d4a7a79c4405cd171d"', 'Server': 'tencent-cos', '
        x-cos-hash-crc64ecma': '7504088481522569214',
         'x-cos-request-id': 'NWYxMmJhOGVfMjNiMjU4NjRfOGE1MF82NWRjOGQ='}
         https://qiaofinn1-1300484618.cos.ap-chengdu.myqcloud.com/others/others-20200718170026525907.jpg
         https://qiaofinn1-1300484618.cos.ap-chengdu.myqcloud.com/others/others-20200718170943473462.jpg

        '''
